package com.hpe.cmca.util.compont;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import sun.misc.BASE64Encoder;

import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.util.List;

/**
 * 创建图片
 */
public class JFreeChartCompont {
    private JFreeChart jfreechart;
    private List<LineData> list;
    private String filePath;
    private Integer weight;
    private Integer height;

    public JFreeChartCompont(List<LineData> list, String filePath, Integer weight, Integer height) {
        this.list = list;
        this.filePath = filePath;
        this.weight = weight;
        this.height = height;
    }


    public JFreeChartCompont creatChart() {
        XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
        XYSeries xyseries3 = new XYSeries("");
        xySeriesCollection.addSeries(xyseries3);
        for (LineData data : list) {
            xyseries3.add(data.getX(), data.getY());
        }

        //        主题样式
        StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
        //设置标题字体
        standardChartTheme.setExtraLargeFont(new Font("宋书", Font.BOLD, 20));
        //设置图例的字体
        standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
        //设置轴向的字体
        standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
        //应用主题样式
        ChartFactory.setChartTheme(standardChartTheme);
        // 创建JFreeChart对象：ChartFactory.createXYLineChart
        jfreechart = ChartFactory.createXYLineChart("", // 标题
                "", // categoryAxisLabel （category轴，横轴，X轴标签）
                "", // valueAxisLabel（value轴，纵轴，Y轴的标签）
                xySeriesCollection, // dataset
                PlotOrientation.VERTICAL,
                true, // legend
                false, // tooltips
                false); // URLs
        // 使用CategoryPlot设置各种参数。以下设置可以省略。
        XYPlot plot = (XYPlot) jfreechart.getPlot();
        plot.setBackgroundPaint(Color.WHITE);
        XYItemRenderer renderer = plot.getRenderer();
        renderer.setSeriesPaint(0, Color.BLUE);
        ValueAxis rangeAxis = plot.getRangeAxis();
        rangeAxis.setVisible(false);
        ValueAxis domainAxis = plot.getDomainAxis();
        domainAxis.setVisible(false);
        LegendTitle legend = jfreechart.getLegend();
        legend.setVisible(false);
        return this;
    }

    public JFreeChartCompont toFile() {
        FileOutputStream out = null;
        try {
            File file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            out = new FileOutputStream(filePath);
            // 保存为PNG
            ChartUtils.writeChartAsPNG(out, jfreechart, weight, height);
            out.flush();
            return this;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // do nothing
                }
            }
        }
        return null;
    }

    public File getFile() {
        File file = new File(filePath);
        if (file.exists()) {
            return new File(filePath);
        }else {
            throw new RuntimeException("没有文件");
        }
    }

    /**
     * List< JFreeChartCompont.LineData> list = new ArrayList<>();
     for (int index = 0; index < 10 ; index++) {
     list.add(new JFreeChartCompont.LineData(new BigDecimal(index),new BigDecimal(index*2)));
     }
     JFreeChartCompont chart = new JFreeChartCompont(list,"D:\\jfreechart\\lineXY2.png",600,400).creatChart();
     chart.getFile();
     String base64 = chart.getBase64();
     * 文件转base64
     * @return
     */
    public String getBase64() {
        File file = this.getFile();
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
            return new BASE64Encoder().encode(buffer).replaceAll("\r|\n", "");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static class LineData {
        private BigDecimal x;
        private BigDecimal y;

        public LineData(BigDecimal x, BigDecimal y) {
            this.x = x;
            this.y = y;
        }

        public BigDecimal getX() {
            return x;
        }

        public void setX(BigDecimal x) {
            this.x = x;
        }

        public BigDecimal getY() {
            return y;
        }

        public void setY(BigDecimal y) {
            this.y = y;
        }
    }
}
